class AuthD::Request
	# NewEmailAddress: any connected user can ask to change its email address.
	IPC::JSON.message NewEmailAddress, 16 do
		property email : String

		def initialize(@email)
		end

		def handle(authd : AuthD::Service, fd : Int32)
			logged_user = authd.get_logged_user_full? fd
			return Response::ErrorMustBeAuthenticated.new if logged_user.nil?

			cloned_user = logged_user.clone

			# In case of a new email address:
			# 1. the new address is stored as "pending_email"
			# 2. the new address has to be validated before being used as primary email address

			# Verify the email address isn't already in the database.
			if authd.users_per_email.get? Base64.encode(@email).chomp
				return Response::ErrorEmailAddressAlreadyUsed.new
			end
			cloned_user.contact.pending_email = @email
			cloned_user.contact.new_activation_key

			begin
				u_login            = cloned_user.login
				u_email            = cloned_user.contact.pending_email.not_nil!
				u_activation_token = cloned_user.contact.activation_key.not_nil!

				# Once the user is created and stored, we try to contact him.
				send_activation_token authd, u_login, u_email, u_activation_token
			rescue e
				Baguette::Log.error "mailer: #{e}"
				return Response::ErrorCannotContactUser.new
			end

			authd.users_per_uid.update cloned_user

			Response::NewEmailTokenSent.new
		end
	end
	AuthD.requests << NewEmailAddress

	# NewEmailAddressToken: validate a pending email address.
	IPC::JSON.message NewEmailAddressToken, 17 do
		property token : String

		def initialize(@token)
		end

		def handle(authd : AuthD::Service, fd : Int32)
			logged_user = authd.get_logged_user_full? fd
			return Response::ErrorMustBeAuthenticated.new if logged_user.nil?

			if logged_user.contact.activation_key.nil?
				return Response::ErrorUserAlreadyValidated.new
			end

			# Remove the user contact activation key: the email is validated.
			if logged_user.contact.activation_key != @token
				return Response::ErrorInvalidActivationKey.new
			end

			cloned_user = logged_user.clone

			cloned_user.contact.activation_key = nil
			cloned_user.contact.email = cloned_user.contact.pending_email
			cloned_user.contact.pending_email = nil

			authd.users_per_uid.update cloned_user

			Response::NewEmailAddressValidated.new cloned_user.contact.email.not_nil!
		end
	end
	AuthD.requests << NewEmailAddressToken
end
